﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace MoneyBook.Windows.Data {
    public sealed class ViewData {
        public static CollectionViewSourceBinderCollection GetCollectionViewSourceBinders(DependencyObject obj) {
            CollectionViewSourceBinderCollection attachables =
                (CollectionViewSourceBinderCollection)obj.GetValue(CollectionViewSourceBindersProperty);
            if (attachables == null) {
                attachables = new CollectionViewSourceBinderCollection();
                obj.SetValue(CollectionViewSourceBindersProperty, attachables);
            }
            return attachables;
        }

        public static readonly DependencyProperty CollectionViewSourceBindersProperty =
            DependencyProperty.RegisterAttached("CollectionViewSourceBinders", typeof(CollectionViewSourceBinderCollection),
            typeof(ViewData), new PropertyMetadata(OnCollectionViewSourceBindersChanged));

        private static void OnCollectionViewSourceBindersChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) {
            IAttachable oldValue = (IAttachable)e.OldValue;
            IAttachable newValue = (IAttachable)e.NewValue;
            if (oldValue != newValue) {
                if ((oldValue != null) && (oldValue.AssociatedObject != null)) {
                    oldValue.Detach();
                }
                if ((newValue != null) && (sender != null)) {
                    if (newValue.AssociatedObject != null) {
                        throw new InvalidOperationException();
                    }
                    newValue.Attach(sender);
                }
            }
        }

    }
}
